<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>EasyUI调研 综合DEMO</title>
    <link rel="stylesheet" type="text/css" href="/Public/assets/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="/Public/assets/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="/Public/assets/css/demo.css">
    <script type="text/javascript" src="/Public/assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="/Public/assets/js/jquery.easyui.min.js"></script>
</head>
<body>
<h2>EasyUI调研 综合DEMO</h2>
<div style="border: solid 1px;width: 500px;">
    <h3>调测信息:</h3>
    <div id="testInfo"></div>
</div>

<div style="border: solid 1px; width: 500px; margin-top: 5px;">
    使用说明：<br>
    1.增加行：将在表格末尾新增一行空的数据<br>
    2.删除行：选定一行后进行删除<br>
    3.点击单元格可进行数值修改<br>
    <br>
    4.上述3个操作进行后都只是在前端进行缓存，如果确认无误，还需要点击“保存修改”，将变更保存至数据库<br>
    5.在进行“保存修改”前，可以点击“撤销修改”，将会把所有未保存操作撤销<br>
</div>

<div style="margin:20px 0;"></div>

<table id="dg" class="easyui-datagrid" title="可编辑数据表" style="width:500px;height:350px;"
       data-options="
				iconCls: 'icon-edit',
				singleSelect: true,
				toolbar: '#tb',
				onClickCell: onClickCell
			">

    <thead>
    <tr>
        <th data-options="field:'id',width:80">ID</th>
        <th data-options="field:'assets',width:80,align:'right',editor:'numberbox'">资产</th>
        <th data-options="field:'liabilities',width:80,align:'right',editor:{type:'numberbox',options:{precision:1}}">负债</th>
        <th data-options="field:'owners_equity',width:80,align:'right',editor:'numberbox'">所有者权益</th>
    </tr>
    </thead>
</table>

<div id="tb" style="height:auto">
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="append()">增加行</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="removeit()">删除行</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true" onclick="accept()">保存修改</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-undo',plain:true" onclick="reject()">撤销修改</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" onclick="getChanges()">查看修改</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" onclick="getAllData()">当页数据</a>
</div>

<br>
<button type="button" onclick="history.go(0);">刷新</button>

<script>
    $.extend($.fn.datagrid.methods, {
        editCell: function(jq,param){
            return jq.each(function(){
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
                for(var i=0; i<fields.length; i++){
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field){
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for(var i=0; i<fields.length; i++){
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });

    var editIndex = undefined;
    function endEditing(){
        if (editIndex == undefined){return true}
        if ($('#dg').datagrid('validateRow', editIndex)){
            $('#dg').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    }
    function onClickCell(index, field){
        if (endEditing()){
            $('#dg').datagrid('selectRow', index)
                .datagrid('editCell', {index:index,field:field});
            editIndex = index;

            var oprec = {id: $('#dg').datagrid('getSelected').id, type: 'm'};
            addOperationRecord(oprec);
        }
    }

    function append(){
        if (endEditing()){
            var tempID = 'A' + ($('#dg').datagrid('getRows').length + 1);
            $('#dg').datagrid('appendRow',{id: tempID});
            editIndex = $('#dg').datagrid('getRows').length-1;

            $('#dg').datagrid('selectRow', editIndex)
                .datagrid('beginEdit', editIndex);

            var oprec = {id: tempID, type: 'a'};
            addOperationRecord(oprec);
        }
    }
    function removeit(){
        if (editIndex == undefined){return}
        var row = $('#dg').datagrid('getSelected');
        if (window.confirm('确定删除ID为 ' + row.id + ' 的整行数据吗？')) {
            $('#dg').datagrid('cancelEdit', editIndex)
                .datagrid('deleteRow', editIndex);
            editIndex = undefined;

            var oprec = {id: row.id, type: 'd'};
            addOperationRecord(oprec);
//            deleteData(row.id);	//调用删除API

            outputTestInfo('删除了ID为 ' + row.id + ' 的整行数据。');
        }

    }
    function accept(){
        if (endEditing()){
            var rows = $('#dg').datagrid('getChanges');
            outputTestInfo('保存了 ' + rows.length+' 行的数据。');

            $('#dg').datagrid('acceptChanges');

            saveOperation(rows);	//将变化数据交由 保存修改统一处理
        }
    }
    function reject(){
        $('#dg').datagrid('rejectChanges');
        editIndex = undefined;

        operationRecord = [];	// 清空操作记录
    }
    function getChanges(){
        var rows = $('#dg').datagrid('getChanges');
        console.log('查看修改的数据');
        console.log(rows);
        outputTestInfo(rows.length+' 行的数据发生了变化!');
    }

    function outputTestInfo(msg) {
        $('#testInfo').html(msg);
    }

    var globalRows = [];
    var operationRecord = [];

    $(function(){
        dataGridRendering();
    });

    function getAllData() {
        var rows = $('#dg').datagrid('getRows');
        var pageNumber = $('#dg').datagrid("options").pageNumber;
        console.log('输出第' + pageNumber + '页的数据');
        console.log(rows);

        outputTestInfo('第' + pageNumber + '页的数据已输出到控制台中！');
    }

    /**
     * 读取数据接口
     */
    function dataGridRendering() {
        $.ajax({
            type: 'GET',
            url: '/index.php/Home/api/getReports',
            success: function (result) {
                $('#dg').datagrid('loadData', result);
                var str = JSON.stringify(result); //系列化对象
                globalRows = JSON.parse(str); //还原
                console.log('渲染表格');
            }
        });
    }

    /**
     * 保存修改统一处理
     */
    function saveOperation(rows) {
        var addArray = [];
        var deleteArray = [];
        var modifyArray = [];
        rows.forEach(function (row, rowIndex, rowArray) {

            var opecType = getOperationRecord(row.id);
            if (opecType == 'a') {
                // 增加数据
                addArray.push(row);
                // addData(row);
            } else if (opecType == 'd') {
                // 删除数据
                deleteArray.push(row.id);
                // deleteData(row.id);
            } else if (opecType == 'm') {
                // 修改数据
                console.log('修改数据');
                modifyArray.push(row);
                // modifyData(row);
            } else if (opecType == 'x') {
                //直接忽略该数据的处理
            } else {
                // 异常情况
                console.log('异常');
            }

        });
        if (addArray.length > 0) {
            addDatas(addArray);
        }
        if (deleteArray.length > 0) {
            deleteDatas(deleteArray);
        }
        if (modifyArray.length > 0) {
            modifyDatas(modifyArray);
        }

    }

    /**
     * 增加操作记录
     */
    function addOperationRecord(oprec) {
        var check = 0;
        for (var i = 0; i < operationRecord.length; i++) {
            if (operationRecord[i].id == oprec.id) {
                if (operationRecord[i].type === 'a') {
                    if (oprec.type === 'm') {
                        // 不覆盖
                    } else if (oprec.type === 'd') {
                        // 抹除该新增数据的记录
                        operationRecord[i].type = 'x';
                    }
                } else if (operationRecord[i].type === 'm') {
                    operationRecord[i].type = oprec.type;
                }
                check = 1;
                return 1;
            }
        }
        if (check === 0) {
            operationRecord.push(oprec);
        }
    }
    // 查询操作记录的类型
    function getOperationRecord(id) {
        for (var i = 0; i < operationRecord.length; i++) {
            if (operationRecord[i].id == id) {
                var result = operationRecord[i].type;
                return result;
            }
        }
    }

    /**
     * 修改数据接口
     */
    function modifyData(row) {
        // console.log('进入');
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/modifyData?XDEBUG_SESSION_START=PHPSTORM',
            data: row,
            success: function (result) {
                console.log(result);
            }
        });
    }
    function modifyDatas(rows) {
        // console.log('进入');
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/modifyDatas',
            data: {datas: rows},
            success: function (result) {
                console.log('增加成功');
                history.go(0);
            }
        });
    }

    /**
     * 删除数据接口
     */
    function deleteData(id) {
        // 直接发送AJAX请求
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/deleteData?XDEBUG_SESSION_START=PHPSTORM',
            data: {id: id},
            success: function (result) {
                console.log(result);
                if (result == 1) {
                    console.log('删除成功');
                }
            }
        });
    }
    function deleteDatas(ids) {
        // 直接发送AJAX请求
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/deleteDatas?XDEBUG_SESSION_START=PHPSTORM',
            data: {ids: ids},
            success: function (result) {
                console.log(result);
                if (result == 1) {
                    console.log('删除成功');
                    history.go(0);
                }
            }
        });
    }

    /**
     * 增加数据接口
     */
    function addData(row) {
        delete row.id;	// 需要将该对象的id去掉
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/addData?XDEBUG_SESSION_START=PHPSTORM',
            data: row,
            success: function (result) {
                console.log(result);
            }
        });
    }
    function addDatas(rows) {
        for (var i = 0; i < rows.length; i++) {
            delete rows[i].id;	// 需要将该对象的id去掉
        }
        $.ajax({
            type: 'POST',
            url: '/index.php/Home/api/addDatas?XDEBUG_SESSION_START=PHPSTORM',
            data: {datas: rows},
            success: function (result) {
                console.log(result);
                history.go(0);
            }
        });
    }

</script>
</body>
</html>